#include <iostream>
#include <pthread.h>
#include <vector>
#include <unistd.h>
using namespace std;
#define N 5
int ticket = 1000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 全局初始化互斥锁；
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;    // 条件变量，等待队列和通知机制；
class ThreadDate
{
public:
    ThreadDate(const string &name)
        : _name(name)
    {
    }
    string _name;
};
void *Ticket(void *args)
{
    pthread_detach(pthread_self());
    ThreadDate *ptr = static_cast<ThreadDate *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        if (ticket < 0)
        {
            pthread_mutex_unlock(&mutex);

            break;
        }
        cout << ptr->_name << " get a ticket" << ticket-- << endl;
        pthread_mutex_unlock(&mutex);

        // 如果不加时间的话，会出现饥饿问题；
        usleep(100);
    }
    return nullptr;
}
int main()
{
    vector<ThreadDate *> _v;
    for (int i = 0; i < N; i++)
    {
        pthread_t tid;
        string name = "thread:";
        name += to_string(i + 1);
        _v.push_back(new ThreadDate(name));
        pthread_create(&tid, nullptr, Ticket, _v[i]);
    }
    while(true)
    {
        sleep(1);
        pthread_cond_signal(&cond);
    }
    return 0;
}